package main
import(
	"fmt"
	"net/http"
	"text/template"
	"strconv"
)

func main(){
	http.HandleFunc("/", index)
	http.HandleFunc("/sum", sum)
	fmt.Println("Listen And Serve ...")
	http.ListenAndServe(":8000", nil)
}

func sum(writer http.ResponseWriter, request *http.Request){
	/*第一步，解析表单*/
	request.ParseForm()
	
	/*第二部，将表单value string转换为数字类型的数据*/
	num1, err1 := strconv.Atoi(request.Form["number1"][0])
	if err1 != nil{
		fmt.Fprintln(writer, "number1 err = ", err1)
	}
	num2, err2 := strconv.Atoi(request.Form["number2"][0])
	if err2 != nil{
		fmt.Fprintln(writer, "number2 err = ", err2)
	}
	
	/*第三步，开始计算两数字的和*/
	var sum int
	sum = num1 + num2
	
	/*第四步，将计算结果反馈给浏览器*/
	fmt.Fprintln(writer, num1, "+", num2, "=", sum)
}

func index(writer http.ResponseWriter, request *http.Request){
	f, err := template.ParseFiles("./form.html")
	
	t := template.Must(f, err)
	
	t.Execute(writer, nil)
}
